package com.xspace.android.xafcommon.adapter;

import android.os.Parcelable;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.view.ViewGroup;

import com.xspace.android.xafcommon.util.BeanUtils;

import java.util.List;


public abstract class BasePagerAdapter<T> extends PagerAdapter implements IAdapter<T> {


	private List<T> listData;

	@Override
	public void addListData(List<T> listData) {
		this.listData.addAll(listData);
	}

	protected void debug(String msg) {

	}

	@Override
	public void destroyItem(ViewGroup container, int position, Object object) {
		debug("destroyItem=" + position);
		((ViewPager) container).removeView((View) object);
	}

	@Override
	public void finishUpdate(View container) {
		debug("finishUpdate");
	}

	@Override
	public int getCount() {
		try {
			return listData.size();
		} catch (Exception e) {
			e.printStackTrace();
			return 0;
		}
	}

	@Override
	public T getData(int position) {
		return listData.get(position);
	}

	public T getItem(int position) {
		try {
			return listData.get(position);
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	@Override
	public T getItemById(Long id) {
		try {
			int count = getCount();
			for (int i = 0; i < count; i++) {
				if (id.equals(getItemId(i))) {
					return getItem(i);
				}
			}
			return null;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	public long getItemId(int position) {
		try {
			return BeanUtils.getId(getItem(position));
		} catch (Exception e) {
			e.printStackTrace();
			return -1;
		}
	}

	@Override
	public List<T> getListData() {
		return listData;
	}

	@Override
	public boolean isViewFromObject(View view, Object object) {
		debug("isViewFromObject=" + object);
		return view.equals(object);
	}

	@Override
	public void restoreState(Parcelable state, ClassLoader loader) {
		debug("restoreState");
	}

	@Override
	public Parcelable saveState() {
		debug("saveState");
		return null;
	}

	@Override
	public void setListData(List<T> listData) {
		this.listData = listData;
	}

	@Override
	public void startUpdate(View container) {
		debug("startUpdate");
	}
}
